package org.liziyi.pss.model.queue;

import org.liziyi.pss.entity.ProcessControlBlock;
import org.liziyi.pss.util.ProcessUtil;

import javax.swing.*;
import javax.swing.table.TableModel;

/**
 * 就绪队列
 *
 * @author liziyi
 */
public class ReadyQueue extends AbstractScheduleQueue {
    public ReadyQueue(TableModel model) {
        super(model);
    }
    @Override
    public synchronized void add(ProcessControlBlock pcb) {
        if(queueList.isEmpty()){
            super.add(pcb);
            return;
        }
        for(int i=0;i<queueList.size();i++){
            if(queueList.get(i).getPriority()>pcb.getPriority()){
                queueList.add(i,pcb);
                int ti=i;
                SwingUtilities.invokeLater(()->{
                    queueTableModel.insertRow(ti,ProcessUtil.pcb2TableRow(pcb));
                });
                return;
            }
        }
        super.add(pcb);
    }

    /**
     * 根据pid从就绪队列中移除进程
     * @param pid
     * @return
     */
    public synchronized ProcessControlBlock remove(int pid) {
        for(int i=0;i<queueList.size();i++){
            if(queueList.get(i).getPid()==pid){
                return super.remove(i);
            }
        }
        return null;
    }
}
